package com.example.homework9.service;

import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.view.View;
import android.widget.Button;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.example.homework9.R;

public class bindService extends Fragment {
    private MyConn myConn;

    public bindService() {
        super(R.layout.bindservice);
    }

    public class MyConn implements ServiceConnection {
        public MusicService2.MyBinder myBinder = null;
        public void onServiceConnected(ComponentName componentName, IBinder service) {
            myBinder = (MusicService2.MyBinder)service;
        }

        public void onServiceDisconnected(ComponentName componentName) {
        }
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        Intent intent = new Intent(getActivity(),MusicService2.class);
        getActivity().startService(intent);

        // bindService
        if (myConn == null) {
            myConn = new MyConn();
            intent = new Intent(getActivity(),MusicService2.class);
            getActivity().bindService(intent,myConn,0);
        }

        // 播放
        Button playMusic2Button = getView().findViewById(R.id.playMusic2Button);
        playMusic2Button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (myConn.myBinder == null) {
                    return;
                }
                myConn.myBinder.play();
            }
        });

        // 下一首
        Button next = getView().findViewById(R.id.next);
        next.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (myConn.myBinder == null) {
                    return;
                }
                myConn.myBinder.next();
            }
        });

        // 暂停
        Button pauseMusic2Button = getView().findViewById(R.id.pauseMusic2Button);
        pauseMusic2Button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (myConn.myBinder == null) {
                    return;
                }
                myConn.myBinder.pause();
            }
        });
    }
}
